<?php
declare (strict_types = 1);
namespace app\api\controller\talk;

use app\LoginController;
use app\model\MyException;
use app\model\table\talk\Talk;
use app\model\tablenot\tool\Tool;
use hg\apidoc\annotation as Apidoc;

/**
 * @Apidoc\Title("聊天")
 */
class TalkController extends LoginController
{

    /**
     * @Apidoc\Title("聊天-定时刷新最新聊天")
     * @Apidoc\Desc ("emoji由前端提供，@@0001（两个@）代表emoji1，@@0002代表emoji1，发送消息内容，前端屏蔽乱七八糟的符号")
     * @Apidoc\Method("GET")
     * @Apidoc\Param ("id", require=true, type="int", desc="刷新到聊天记录的最后一通消息,第一次拉取值传0")
     */
    public function flushTalkAction()
    {
        Tool::checkParam(['id'],$this->get);
        $id = $this->get['id'];
        $unionId = $this->user['union_id'];
        $where = array();
        $where[] = ['union_id', '=', $unionId];
        if($id == 0){
            // 返回最近10条消息
            $where['orderBy'] = "created_at desc";
            $where['limit'] = 10;
            $objs = Talk::instance()->findMore($where);
            $objs = array_reverse($objs);
        }else{
            // 返回id之后的消息
            $where[] = ['id', '>', $id];
            $objs = Talk::instance()->findMore($where);
        }
        $JoinWith=['UserInfo'];
        Talk::instance()->dealJoinWith($objs,$JoinWith);
        $this->setData($objs);
        $this->sendJson();
    }

    /**
     * @Apidoc\Title("用户-发送消息")
     * @Apidoc\Method("POST")
     * @Apidoc\Param ("content", require=true, type="int", desc="消息")
     */
    public function addAction()
    {
        try {
            Tool::checkParam(['content'],$this->post);
            $userId = $this->user['id'];
            $unionId = $this->user['union_id'];
            $content = $this->post['content'];
            // 首先判断发送消息频率
            //Talk::instance()->checkLimit($userId);

            $postData = array(
                'user_id' => $userId,
                'union_id' => $unionId,
                'content' => $content,
                'created_at' => $this->time,
            );
            Talk::instance()->addOne($postData);
            $this->sendJson();
        } catch (MyException $e) {
            echo $e->toJson();
        }
    }


}
